package per.hnvcam.searchext.controller.administration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import per.hnvcam.searchext.Constants;
import per.hnvcam.searchext.data.model.Statistic;
import per.hnvcam.searchext.services.StatisticService;

import java.util.Arrays;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: camhoang
 * Date: 3/6/12
 * Time: 9:30 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class StatisticController {

   private static final String STATISTIC_PAGE = "administration/statistic";

   @Autowired
   @Qualifier("StatisticService")
   private StatisticService statisticService;

   @RequestMapping(value = "/administration/statistic.jhtml", method = RequestMethod.GET)
   public String showStatistic(@RequestParam(value = "operation", required = false) String operation, Model model) {
      if (Constants.OPERATION_GENERATE_STATISTIC.equals(operation)) {
         statisticService.generateStatistic();
      }
      Statistic statistic = statisticService.getLastStatistic();
      if (statistic != null) {
         model.addAttribute("percentage", statisticService.getPercentage(statistic));
         model.addAttribute("showStatistic", true);
      } else {
         model.addAttribute("showStatistic", false);
      }

      List historicalStatistic = statisticService.getRecentStatistic(10);
      List graphData = statisticService.convertToGraphData(historicalStatistic);
      if (graphData != null) {
         model.addAttribute("lineChartLabels", Arrays.toString((String []) graphData.get(0)));
         model.addAttribute("lineChartKeys", "['Number of samples', 'Percentage', 'Rule Set size']");
         model.addAttribute("lineChartData1", Arrays.toString((int[]) graphData.get(5)));
         model.addAttribute("lineChartData2", Arrays.toString((int []) graphData.get(6)));
         model.addAttribute("lineChartData3", Arrays.toString((int []) graphData.get(4)));
         model.addAttribute("lineChartTooltip1", convertToToolTip((int []) graphData.get(5)));
         model.addAttribute("lineChartTooltip2", convertToToolTip((int []) graphData.get(6)));
         model.addAttribute("lineChartTooltip3", convertToToolTip((int []) graphData.get(4)));
      }
      return STATISTIC_PAGE;
   }

   private String convertToToolTip(int [] array) {
      String [] replicate = new String [array.length];
      for (int i = 0; i < array.length; i++) {
         replicate[i] = "'" + String.valueOf(array[i]) + "'";
      }
      return Arrays.toString(replicate);
   }
}
